package cn.tedu.antcolony.passport.controller;

import cn.tedu.antcolony.passport.pojo.dto.AdminLoginInfoDTO;
import cn.tedu.antcolony.passport.pojo.param.AdminAddNewParam;
import cn.tedu.antcolony.passport.pojo.param.AdminLoginParam;
import cn.tedu.antcolony.passport.pojo.param.AdminUpdatePassword;
import cn.tedu.antcolony.passport.pojo.param.UpdateAdminParam;
import cn.tedu.antcolony.passport.pojo.vo.AdminListItemVO;
import cn.tedu.antcolony.passport.pojo.vo.AdminStandardVO;
import cn.tedu.antcolony.passport.service.IAdminService;
import cn.tedu.antcolonycommons.consts.HttpConsts;
import cn.tedu.antcolonycommons.pojo.vo.PageData;
import cn.tedu.antcolonycommons.security.LoginPrincipal;
import cn.tedu.antcolonycommons.web.JsonResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/admin")
@Api(tags = "01.管理员模块")
@Slf4j
@Validated
@CrossOrigin
public class AdminController {
    @Autowired
    private IAdminService iAdminService;

    /**
     * 添加管理员
     *
     * @param adminAddNewParam
     * @return
     */
    @PreAuthorize("hasAuthority('/ams/admin/add-new')")//添加权限
    @PostMapping("/addNew")
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    public JsonResult<Void> addNew(@Validated AdminAddNewParam adminAddNewParam) {
        log.debug("开始执行【添加管理员】请求");
        iAdminService.addNew(adminAddNewParam);
        return JsonResult.ok();
    }

    /**
     * 修改密码
     *
     * @param adminUpdatePassword
     * @return
     */
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/updatePassword/{id}")
    @ApiOperation("修改密码")
    @ApiOperationSupport(order = 200)
    public JsonResult<Void> updatePassword(@Validated AdminUpdatePassword adminUpdatePassword, @PathVariable("id") Long id) {
        iAdminService.updatePassword(adminUpdatePassword, id);
        return JsonResult.ok();
    }

    /**
     * 根据id修改管理员基本信息
     *
     * @param updateAdminParam
     * @return
     */
    @PostMapping("/updateByAdminId/{id}")
    @ApiOperation("根据id修改管理员基本信息")
    @ApiOperationSupport(order = 700)
    public JsonResult<Void> updateByAdminId(@Validated UpdateAdminParam updateAdminParam, @PathVariable("id") Long id) {
        iAdminService.updateAdmin(updateAdminParam, id);
        return JsonResult.ok();
    }

    @GetMapping("/getAdminById/{id}")
    public JsonResult<AdminStandardVO> getAdminById(@PathVariable Long id) {
        AdminStandardVO adminById = iAdminService.getAdminById(id);
        return JsonResult.ok(adminById);
    }

    /**
     * 查询管理员列表
     *
     * @param page
     * @return
     */
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    @GetMapping("/list/{page}")
    @ApiOperation("查询管理员列表")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int")
    })
    public JsonResult<PageData> list(@NotNull(message = "必须提交页码数") @Range(min = 1, message = "请提交有效的页码") @PathVariable("page") Integer page) {
        PageData<AdminListItemVO> adminListItemVOPageData = iAdminService.adminList(page);
        return JsonResult.ok(adminListItemVOPageData);
    }


    /**
     * 管理员登录
     *
     * @param adminLoginParam
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/login")
    public JsonResult<AdminLoginInfoDTO> login(AdminLoginParam adminLoginParam, @ApiIgnore HttpServletRequest request) throws JsonProcessingException {
        log.debug("开始处理【管理员登录请求:】,参数:{}", adminLoginParam);
        //获取登录 ip
        String remoteAddr = request.getRemoteAddr();
        //客户端 登录浏览器
        String userAgent = request.getHeader(HttpConsts.HEADER_USER_AGENT);
        AdminLoginInfoDTO adminLoginInfoDTO = iAdminService.adminLogin(adminLoginParam, remoteAddr, userAgent);
        return JsonResult.ok(adminLoginInfoDTO);
    }


    /**
     * @param loginPrincipal
     * @return
     * @AuthenticationPrincipal UserDetails userDetails 获取当事人信息
     * @ApiIgnore 可以用在类、方法上，方法参数中，用来屏蔽某些接口或参数，使其不在页面上显示。
     */
    @GetMapping("/list")
    public JsonResult<Void> list(@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("当事人的id:{}", loginPrincipal.getId());
        log.debug("当事人的用户名:{}", loginPrincipal.getUsername());
        //log.debug("当事人的密码:{}",adminLoginInfoVo.getPassword());
        //log.debug("当事人的账号是否启用:{}",adminLoginInfoVo.getEnable()==1? true:false);
        //return adminLoginInfoVo.getEnable()==1? JsonResult.ok() : JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED_DISABLED,"账号未启用!");

        //admin:jwt:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiZXhwIjoxNjg1ODU3MDcwLCJ1c2VybmFtZSI6InJvb3QxIn0.QkVhhKugfKWPfP5qJvCKUd84wrrBlEJyyz1Oc7ST_1s
        return JsonResult.ok();
    }


    @PostMapping("/adminLogOut")
    @ApiOperation("管理员退出登录")
    @ApiOperationSupport(order = 500)
    public JsonResult<Void> adminLogOut(@RequestHeader(HttpConsts.HEADER_AUTHORIZATION) String jwtToken) {
        iAdminService.adminLogOut(jwtToken);
        return JsonResult.ok();
    }


    /**
     * 根据id删除管理员
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteAdminById/{id}")
    @ApiOperation("根据id删除管理员")
    @ApiOperationSupport(order = 600)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员id", required = true, example = "1", type = "long")
    })
    public JsonResult<Void> deleteAdminById(@PathVariable("id") @Range(min = 1, message = "请提交有效的id值") Long id) {
        iAdminService.deleteAdminById(id);
        return JsonResult.ok();
    }


}
